package com.chookss.mine.set;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.chookss.BuildConfig;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.mine.entity.AccountEntity;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.address.AddressDialog;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserInfosActivity extends BaseAct {
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.circlePersonalIcon)
    CircleImageView circlePersonalIcon;
    @BindView(R.id.tvNickname)
    TextView tvNickname;
    @BindView(R.id.tvUserId)
    TextView tvUserId;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.iv_notice_vibration)
    ImageView ivNoticeVibration;
    @BindView(R.id.tvBirth)
    TextView tvBirth;
    @BindView(R.id.tvJob)
    TextView tvJob;
    @BindView(R.id.tvDepartment)
    TextView tvDepartment;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.tvIntroduce)
    TextView tvIntroduce;
    @BindView(R.id.tvLevel)
    TextView tvLevel;
    @BindView(R.id.tvRealName)
    TextView tvRealName;
    @BindView(R.id.llLevel)
    LinearLayout llLevel;
    @BindView(R.id.lineLevel)
    View lineLevel;
    private MineInfoEntity mineInfoEntity;
    private int RESULT_LOAD_IMAGE = 3;//选择图片
    private int RESULT_TAKE_PHOTO = 4;//拍照
    private int EDIT_INFOS = 6;   //修改用户资料
    private String cameraImageName;
    private String originalUrl = null, thumbUrl = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        initState();
        common_title_txt.setText("个人资料");
        common_right_txt.setText("保存");
        common_right_txt.setVisibility(View.VISIBLE);
        getData();
        selectEmployeeDetail();
        NavigationTools.setWaterMark(this, "18");
    }

    public void updateData() {
        if (mineInfoEntity == null) {
            return;
        }
        originalUrl = mineInfoEntity.getHeadPhotoUrl();
        thumbUrl = mineInfoEntity.getHeadPhotoThumbUrl();
        GlideUtils.loadAvatar(UserInfosActivity.this, thumbUrl, circlePersonalIcon);
        tvNickname.setText(mineInfoEntity.getNickName());
        tvUserId.setText(mineInfoEntity.getEmployeeCode());
        tvSex.setText(mineInfoEntity.getSex());
        tvBirth.setText(mineInfoEntity.getBirthDate());
        tvJob.setText(mineInfoEntity.getPost());
        tvLocation.setText(mineInfoEntity.getAddress());
        tvIntroduce.setText(mineInfoEntity.getEmployeeProfile());
        tvDepartment.setText(mineInfoEntity.getBelgOrgName());
        if (Utils.isNull(mineInfoEntity.getLevelName())) {
            llLevel.setVisibility(View.GONE);
            lineLevel.setVisibility(View.GONE);
        } else {
            llLevel.setVisibility(View.VISIBLE);
            lineLevel.setVisibility(View.VISIBLE);
            tvLevel.setText(mineInfoEntity.getLevelName());
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.getMyInfo, SignUtils2.makeSignStr(map), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) throws Exception {
                mineInfoEntity = data;
                updateData();
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }
    private void selectEmployeeDetail() {
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        map.put("type","1");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.selectEmployeeDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) throws Exception {
                 if(Utils.isNull(data.getRegisteredNumber())){
                     tvRealName.setText("未认证");
                 }else{
                     tvRealName.setText("已认证");
                 }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }
    private void upLoadData() {
        if (tvNickname == null) {
            return;
        }
        Map<String, String> allmap = new HashMap<>();
        allmap.put("nickName", tvNickname.getText().toString());
        allmap.put("sex", tvSex.getText().toString());
        allmap.put("birthDate", tvBirth.getText().toString());
//        allmap.put("post", tvJob.getText().toString());
        allmap.put("address", tvLocation.getText().toString());
        allmap.put("employeeProfile", tvIntroduce.getText().toString());
        allmap.put("headPhotoUrl", originalUrl);
        allmap.put("headPhotoThumbUrl", thumbUrl);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.updateMyInfo, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) throws Exception {
                dismissLoading();
                MyToast.show("资料修改成功");
                ;
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }

    /**
     * 展示时间选择弹窗
     */
    private void ShowPickDialog() {
        cameraImageName = System.currentTimeMillis() + Urls.cameraPicSuffix;
        Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.my_img_popule_xml, null);
        LinearLayout ll_camera = view.findViewById(R.id.ll_camera);
        LinearLayout ll_gallery = view.findViewById(R.id.ll_gallery);
        Button ll_cancle = view.findViewById(R.id.ll_cancle);
        ImageView iv_leftBack = view.findViewById(R.id.iv_leftBack);
        ImageView iv_rightClose = view.findViewById(R.id.iv_rightClose);
        ll_cancle.setOnClickListener(v -> dialog.dismiss());
        iv_leftBack.setOnClickListener(v -> dialog.dismiss());
        iv_rightClose.setOnClickListener(v -> dialog.dismiss());
        ll_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestCamera();
                dialog.dismiss();
            }
        });
        ll_gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestAlbumPermission();
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    /**
     * 存储权限获取
     */
    private void requestAlbumPermission() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        KLog.i("hasPermission");
                        if (all) {
                            Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                            intent1.setDataAndType(
                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    "image/*");
                            startActivityForResult(intent1, RESULT_LOAD_IMAGE);
                        } else {
                            PermissionUtils.errorSinglePermission(granted);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(UserInfosActivity.this, denied, quick);
                    }
                });
    }

    /**
     * 照相机权限获取
     */
    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            openCamera();
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(UserInfosActivity.this, denied, quick);
                    }
                });
    }

    /**
     * 打开照相机
     */
    private void openCamera() {
        File temp = new File(getExternalFilesDir(Urls.IMAGEFOLDER), cameraImageName);
        if (temp.exists()) {
            temp.deleteOnExit();
        }
        Intent intent2 = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", temp);
            intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            imageUri = Uri.fromFile(temp);
        }
        // 下面这句指定调用相机拍照后的照片存储的路径
        intent2.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent2, RESULT_TAKE_PHOTO);
    }

    /**
     * @param file 图片压缩
     */
    private void upImage(File file) {
        // 获得文件路
        //压缩图片
        Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
        options.quality = 95;
        options.size = 1024 * 512;
        Tiny.getInstance().source(file).asFile().withOptions(options).compress(new FileCallback() {
            @Override
            public void callback(boolean isSuccess, String outfile, Throwable t) {
                if (isSuccess) {
                    KLog.i(outfile);
                    File newFile = new File(outfile);
                    finalUpLoadImg(newFile);
                } else {
                    finalUpLoadImg(file);
                }
            }
        });
    }

    private void finalUpLoadImg(File file) {
        showLoading();
        if (file != null && !file.toString().equals("")) {
            // TODO: 2018/7/20  upload img
            MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "1", file, new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    JSONObject data = null;
                    try {
                        result = new JSONObject(response.body());
                        if ("200".equals(result.getString("code"))) {
                            data = result.getJSONObject("data");
                            originalUrl = data.getString("originalUrl");
                            thumbUrl = data.getString("originalUrl");
                            String employeecode = new ShareUtils().getString(UserInfosActivity.this, StaticClass.EMPLOYEECODE, "");
                            new ShareUtils().putString(UserInfosActivity.this, StaticClass.USER_AVATAR_URL, thumbUrl + "?x-oss-process=image/resize,m_lfit,h_150,w_150");
                            new ShareUtils().putString(UserInfosActivity.this, StaticClass.ORIGINALURL, originalUrl + "?x-oss-process=image/resize,m_lfit,h_150,w_150");
                            List<AccountEntity> list = XJson.getAccountsList(UserInfosActivity.this, new ShareUtils().getString(UserInfosActivity.this, StaticClass.APPACCOUNT, ""), AccountEntity.class);
                            for (int i = 0; i < list.size(); i++) {
                                if (employeecode.equals(list.get(i).getEmployeeCode())) {
                                    list.get(i).setHeadPhotoThumbUrl(thumbUrl + "?x-oss-process=image/resize,m_lfit,h_150,w_150");
                                    XJson.setAccountsList(UserInfosActivity.this, new ShareUtils().getString(UserInfosActivity.this, StaticClass.APPACCOUNT, ""), list);
                                }
                            }
                            if (circlePersonalIcon != null)
                                GlideUtils.loadAvatar(UserInfosActivity.this, thumbUrl + "?x-oss-process=image/resize,m_lfit,h_150,w_150", circlePersonalIcon);
                            upLoadData();
                        } else {
                            if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            } else {
                                MyToast.show(result.getString("msg"));
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                }
            });
        } else {
            dismissLoading();
            MyToast.show("数据异常，请重试");
        }
//        if (null != dialoga && !dialoga.isShowing()) dialoga.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        KLog.i(requestCode + "--" + resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == RESULT_LOAD_IMAGE) {
                // 如果是直接从相册获取
                String imageSDCardPath = PathUtil.getPath(UserInfosActivity.this, data.getData());
                upImage(new File(imageSDCardPath));
            } else if (requestCode == RESULT_TAKE_PHOTO) {
                // 如果是调用相机拍照时
                File temp = new File(getExternalFilesDir(Urls.IMAGEFOLDER), cameraImageName);
                upImage(temp);
            }
        }
        if (requestCode == EDIT_INFOS) {
            //资料修改
            if (data == null) {
                return;
            }
            switch (resultCode) {
                case 1:
                    if (tvNickname == null) {
                        return;
                    }
                    String nickName = data.getStringExtra("newNickName");
                    tvNickname.setText(nickName);
                    break;
                case 2:
                    if (tvSex == null) {
                        return;
                    }
                    String sex = data.getStringExtra("newSex");
                    tvSex.setText(sex);
                    break;
                case 4:
                    if (tvIntroduce == null) {
                        return;
                    }
                    String profile = data.getStringExtra("newProfile");
                    tvIntroduce.setText(profile);
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("RefreshUserDetail")) {
                tvRealName.setText("已认证");
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.rlMore, R.id.rlRealName, R.id.common_right_txt, R.id.rl_personalData_icon, R.id.rl_personalData_sex, R.id.rlBirthday, R.id.rlLocation, R.id.rlProfile})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                upLoadData();
                break;
            case R.id.rl_personalData_icon:
                ShowPickDialog();
                break;
//            case R.id.rl_personalData_name:
//                intent = new Intent(this, NickNameActivity.class);
//                intent.putExtra("nick", tvNickname.getText().toString());
//                startActivityForResult(intent, EDIT_INFOS);
//                break;
            case R.id.rl_personalData_sex:
                intent = new Intent(this, SexActivity.class);
                startActivityForResult(intent, EDIT_INFOS);
                break;
            case R.id.rlBirthday:
                if (tvBirth == null) {
                    return;
                }
                showDatePickDialog(tvBirth.getText().toString());
                break;
            case R.id.rlLocation:
                showAddressPickerPop();
                break;
            case R.id.rlProfile:
                intent = new Intent(this, ProfileActivity.class);
                intent.putExtra("profile", tvIntroduce.getText().toString());
                startActivityForResult(intent, EDIT_INFOS);
                break;
            case R.id.rlRealName:
                intent = new Intent(this, RealNameActivity.class);
                startActivity(intent);
                break;
            case R.id.rlMore:
                intent = new Intent(this, UserMoreInfoActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * @param curDate 时间选择
     */
    private void showDatePickDialog(String curDate) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        int year = 0, month = 0, day = 0;
        try {
            if (Utils.isNull(curDate)) {
                year = calendar.get(Calendar.YEAR);
                month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);
            } else {
                year = Integer.parseInt(curDate.substring(0, curDate.indexOf("-")));
                month = Integer.parseInt(curDate.substring(curDate.indexOf("-") + 1, curDate.lastIndexOf("-"))) - 1;
                day = Integer.parseInt(curDate.substring(curDate.lastIndexOf("-") + 1, curDate.length()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
        }
        if (tvBirth == null) {
            return;
        }
        //构建一个日期对话框，该对话框已经集成了日期选择器
        //DatePickerDialog的第二个构造参数指定了日期监听器
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                tvBirth.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
            }
        },
                year,
                month,
                day);
        //把日期对话框显示在界面上
        dialog.show();
    }

    /**
     * 地址选择
     */
    private void showAddressPickerPop() {
        new AddressDialog.Builder(this)
                //.setTitle("选择地区")
                // 设置默认省份
//                .setProvince(mProvince)
                // 设置默认城市（必须要先设置默认省份）
//                .setCity(mCity)
                // 不选择县级区域
                .setIgnoreArea()
                .setListener((dialog, province, city, area) -> {
                    String address = province + city;
                    if (!tvLocation.getText().toString().equals(address)) {
                        tvLocation.setText(address);
                    }
                })
                .show();
    }

    @Override
    public void initData() {

    }
}
